package org.sword.wechat4j.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.sword.wechat4j.exception.WeChatException;
import org.sword.wechat4j.exception.WeChatReturnCode;

import com.alibaba.fastjson.JSONObject;
/**
 * 工具类
 * @author 吴人龙
 */
public class WeChatUtil {
	/**
	 * 判断是否请求成功
	 * @param resultStr
	 * @throws WeChatException
	 */
	public static void isSuccess(String resultStr) throws WeChatException{		
		JSONObject jsonObject = JSONObject.parseObject(resultStr);
		Integer errCode =jsonObject.getIntValue("errcode");
		if (errCode!=null && errCode!=0) {
			String errMsg = WeChatReturnCode.getMsg(errCode);
			if (errMsg.equals("")) {
				errMsg = jsonObject.getString("errmsg");
			}
			throw new WeChatException("异常码:"+errCode+";异常说明:"+errMsg);
		}
	}
	
	/**
	 * 转换编码
	 * @param content
	 * @return
	 */
	public static String toUtf8(String content){
		try {
			if(StringUtils.isNotBlank(content)){
				content = new String(content.getBytes("ISO8859-1"),"UTF-8");
			}
		}catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return content;
	}
	
	/**
	 * 时间戳转日期格式
	 * @param seconds
	 * @return
	 */
	public static Date timeStampToDate(String seconds) {  
        if(StringUtils.isBlank(seconds)){  
            return null;  
        }
        return new Date(Long.valueOf(seconds+"000"));  
    }  
	
	/**
	 * 判断字符串中是否包含Emoji表情符
	 * @param content
	 * @return
	 */
	public static boolean isEmoji(String content){
		boolean success = false;
		Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",Pattern.UNICODE_CASE| Pattern.CASE_INSENSITIVE);
		Matcher emojiMatcher = emoji.matcher(content);
		if(emojiMatcher.find()) {
			success = true;
		}
		return success;
	}
}
